import React, {useEffect, useRef, useState} from 'react'
import './index.css'
import LivePlay from './components/live-player/index'
import {Button, Form, Input, Modal, Select, Badge, Tooltip, message, Radio, Row, Col} from "antd";
import {AudioOutlined} from '@ant-design/icons';
import {useRequest} from "@umijs/hooks";
import {url} from "@/utils/url";
import {fetchRequest} from "@/utils/Request";
// @ts-ignore
import shortid from 'shortid'

const {Item} = Form
const {Search} = Input
const {Option} = Select

const Index = () => {

    const [isModalVisible, setIsModalVisible] = useState(false);
    const isShow = useRef(false)
    const [form] = Form.useForm();
    const [collegeId, setCollegeId] = useState('')
    const [deviceName, setDeviceName] = useState('')

    const {data} = useRequest(() => fetchRequest(url.GET_SCHOOL_ORGANIZATION, {
        "level": 0,
        "treeId": "0"
    }), {
        onSuccess: (data) => {
            setCollegeId(data?.data[0]?.value)
        }
    })


    const {data: device, run} = useRequest((params) => fetchRequest(url.DEVICE_LIST, params), {
        manual: true,
        onSuccess: (data) => {
            if (!data.success) {
                message.error(data.errorMsg)
            }
        }
    })

    useEffect(() => {


        if (collegeId) {
            run({
                collegeId: collegeId,
                deviceName: ""
            })
        }


    }, [collegeId])
    const [type, setType] = useState('one')
    const [list, setList] = useState<any[]>([{id: shortid.generate(), check: true}])
    const handleChange = (value: any) => {
        setType(value.target.value)

        if (value.target.value === 'one') {


            setList([{...list[0]}])

        } else {
            setList([...list, {id: shortid.generate()}, {id: shortid.generate()}, {id: shortid.generate()}])
        }

    }
    const handleOk = () => {
        form.submit()
        setIsModalVisible(false);

    };
    const onFinish = (values: any) => {
        setCollegeId(values?.collegeId)
        setType('one')
        setList([{id: shortid.generate(), check: true}])


    }
    const handleCancel = () => {
        setIsModalVisible(false);
    };
    const onSearch = async (value: any) => {

        setDeviceName(value)

        isShow.current = !!value


    }
    useEffect(() => {
        if (collegeId) {

            run({
                collegeId: collegeId,
                deviceName: deviceName
            })
        }

    }, [deviceName])
    const changeItem = (item: any) => {

        const index = list.findIndex((i) => i.deviceId === item.deviceId);


        if (index === -1) {
            //拿到Index直接替换


            const i = list.findIndex((i) => i.deviceId === undefined)


            setList((list) => {
                if (type === 'one') {
                    //停止播放
                    list[0]?.player?.dispose()
                    item.check = true
                    return [item]
                } else {


                    const flag = list.every(item => {
                        return 'deviceId' in item
                    })


                    if (flag) {
                        const e = list.findIndex(item => item.check)
                        list[e]?.player?.dispose()
                        item.check = true
                        list[e] = item
                    } else {
                        item.check = list[i]?.check
                        list[i] = item

                    }

                    return [...list]
                }
            })

        }

    }
    //点击的video
    const onVideo = (index: number) => {


        setList((list) => list.map((item, i) => {
            item.check = i === index;
            return item
        }))
    }
    const getPlayer = (player: any, deviceId: string) => {
        setList((list) => list.map((item) => {

            if (item.deviceId === deviceId)
                item.player = player
            return item
        }))
    }

    const itemChange = (value: any) => {


        const index = list.findIndex(item => item.deviceId == value)

        console.log(index)


        if (index === -1) {
            const item = device?.data?.rows.find((k: any) => k.deviceId === value)
            changeItem(item)
        } else {
            message.info('已有视频正在播放')
        }
    }


    return (<div className={'video-wrap'}>
        <div className={'video'}>
            <div className={'monitor-list-wrap'}>
                <div className={'monitor-title'}>
                    {data?.data.find((item: any) => item.value == collegeId)?.label}
                    <Button type="link" onClick={() => setIsModalVisible(true)} className={'switch'}>切换</Button>
                </div>
                <div>
                    <Search placeholder="请输入监控名称" onSearch={onSearch}/>
                    <div
                        className={'show-count'}>{isShow.current ? '搜索结果' : `当前在线${device?.data?.onlineNum}/${device?.data?.count}`}</div>
                    <div className={'monitor-list'}>
                        {device?.data?.rows.map((item: any) => {

                            return item?.terminalState === '1' ?

                                <div
                                    className={`monitor-item ${list.findIndex(k => k.deviceId === item.deviceId) >= 0 ? "checker" : ''}`}
                                    key={item.deviceId}
                                    onClick={() => changeItem(item)}>
                                    <span>{item.deviceName}</span>


                                    <Badge status="success"/>
                                </div>

                                :


                                <Tooltip title="设备离线" key={item.deviceId}>
                                    <div className={'monitor-item  lx'}>
                                        <span>{item.deviceName}</span>
                                        <Badge status="error"/>
                                    </div>
                                </Tooltip>

                        })}


                    </div>
                </div>
            </div>
            <div className={'video-item'}>
                <div className={'videoSurveillance-title'}>
                    <Radio.Group value={type} onChange={handleChange}>
                        <Radio.Button value="one" className={'onlyOne'}>
                            <span className={'box'}/>
                        </Radio.Button>
                        <Radio.Button value="four" className={'onlyFour'}>
                            <span className={'box'}/>
                            <span className={'box'}/>
                            <span className={'box'}/>
                            <span className={'box'}/>
                        </Radio.Button>
                    </Radio.Group>
                </div>
                <Row gutter={[8, 8]}>
                    {list.map((item, i) => <Col span={list.length === 1 ? 24 : 12} key={i}>
                        <div
                            className={`${list.length === 4 ? 'showImgFour' : 'showImg'} ${item.check ? 'border' : ''} `}
                            onClick={() => onVideo(i)}>
                            {item.deviceId ? <div className={'showImg-item'}>
                                <Select style={{width: 200}} value={item.deviceId} onChange={itemChange}>
                                    {device?.data?.rows.map((deviceItem: any, i: number) => <Option
                                        value={deviceItem.deviceId} key={i}
                                        disabled={deviceItem?.terminalState === '2'}>
                                        <div className='showImg-item-title'>
                                            <span>{deviceItem.deviceName}</span>
                                            <Badge status={deviceItem?.terminalState === '1' ? 'success' : 'error'}/>
                                        </div>
                                    </Option>)}
                                </Select>
                            </div> : null}
                            <LivePlay{...item} getPlayer={getPlayer}/>
                        </div>
                    </Col>)}
                </Row>

            </div>
        </div>


        <Modal title="选择学校" visible={isModalVisible} onOk={handleOk} onCancel={handleCancel}>
            <Form form={form} onFinish={onFinish}>
                <Item label="学校"
                      name="collegeId">
                    <Select placeholder={'请选择学校'}>
                        {data?.data?.map((item: any) => <Select.Option value={item.value}
                                                                       key={item.value}>{item.label}</Select.Option>)}
                    </Select>
                </Item>
            </Form>
        </Modal>
    </div>)


}


export default Index


